// 封装购物车模块
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useUserStore } from './userStore'
import { insertCartAPI, findNewCartListAPI, delCartAPI } from '@/api/cart'


export const useCartStore = defineStore('cart', () => {
  const userStore = useUserStore()
  const isLogin = computed(()=>userStore.userInfo.token)
  // 1. 定义state - cartList
  const cartList = ref([])

  //获取最新购物车列表
  const updateNewList = async ()=>{
    const res = await findNewCartListAPI()
    cartList.value = res.result
  }
  // 2. 定义加入购物车
  const addCart = async (goods) => {
   if(isLogin.value){
    const { skuId, count } = goods
      // 登录之后的加入购车逻辑
      await insertCartAPI({ skuId, count })
      updateNewList()
   }else{
    console.log('添加', goods)
    // 添加购物车操作
    // 已添加过 - count + 1
    // 没有添加过 - 直接push
    // 思路：通过匹配传递过来的商品对象中的skuId能不能在cartList中找到，找到了就是添加过
    const item = cartList.value.find((item) => goods.skuId === item.skuId)
    if (item) {
      // 找到了
      item.count++
    } else {
      // 没找到
      cartList.value.push(goods)
    }
   }
  }
  // 删除购物车
  const delCart = async (skuId) => {
    if (isLogin.value) {
      // 调用接口实现接口购物车中的删除功能
      await delCartAPI([skuId])
      updateNewList()
    } else {
      // 思路：
      // 1. 找到要删除项的下标值 - splice
      // 2. 使用数组的过滤方法 - filter
      const skuIdIndex = cartList.value.findIndex((item) => item.skuId===skuId)
    cartList.value.splice(skuIdIndex,1)
    }
  }

  const totalCount = computed(() => cartList.value.reduce((sum, item)=> sum + item.count, 0))
  const totalPrice = computed(() => cartList.value.reduce((sum, item)=> sum + item.count * 125, 0))//item.price没有price的属性

  // 单选功能
  const singleCheck = (skuId, selected) => {
    // 通过skuId找到要修改的那一项 然后把它的selected修改为传过来的selected
    const item = cartList.value.find((item) => item.skuId === skuId)
    item.selected = selected
  }

  //是否全选
  const isSelect =  computed(() => cartList.value.every(item =>item.selected))

  // 全选功能action
  const allSelect = (selected) => {
    // 把cartList中的每一项的selected都设置为当前的全选框状态
    cartList.value.forEach(item => item.selected = selected)
  }

// 3. 已选择数量
  const selectedCount = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count, 0))
  // 4. 已选择商品价钱合计
  const selectedPrice = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count * 125, 0))

  //清除购物车
  const clearCart = () => {
    cartList.value = []
  }

  return {
    cartList,
    totalCount,
    totalPrice,
    isSelect,
    selectedCount,
    selectedPrice,
    addCart,
    delCart,
    singleCheck,
    allSelect,
    clearCart,
    updateNewList
  }
}, {
  persist: true,
})
